package com.bee.member.controller;

import com.alibaba.fastjson.JSONObject;
import com.bee.base.BaseResponse;
import com.bee.constants.Constants;
import com.bee.member.feign.MemberLoginServiceFeign;
import com.bee.member.input.dto.UserLoginInpDTO;
import com.bee.member.vo.LoginVo;
import com.bee.web.base.BaseWebController;
import com.bee.web.bean.MeiteBeanUtils;
import com.bee.web.constants.WebConstants;
import com.bee.web.utils.CookieUtils;
import com.bee.web.utils.RandomValidateCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController extends BaseWebController {
	/**
	 * 跳转到登陆页面页面
	 */
	private static final String MB_LOGIN_FTL = "member/login";
	/**
	 * 重定向到首页
	 */
	private static final String REDIRECT_INDEX = "redirect:/";
	@Autowired
	private MemberLoginServiceFeign memberLoginServiceFeign;

	/**
	 * 跳转页面
	 *
	 * @return
	 */
	@GetMapping("/login")
	public String getLogin() {
		return MB_LOGIN_FTL;
	}

	/**
	 * 接受请求参数
	 *
	 * @return
	 */
	@PostMapping("/login")
	public String postLogin(@ModelAttribute("loginVo") LoginVo loginVo, Model model, HttpServletRequest request,
							HttpServletResponse response, HttpSession httpSession) {
		//1.图形验证码
		if(!RandomValidateCodeUtil.checkVerify(loginVo.getGraphicCode(),httpSession)){
			setErrorMsg(model, "验证码不正确");
			return MB_LOGIN_FTL;
		};
		//2.登录
		UserLoginInpDTO dto = MeiteBeanUtils.voToDto(loginVo, UserLoginInpDTO.class);
		//设置登录设备信息
		dto.setLoginType(Constants.MEMBER_LOGIN_TYPE_PC);
		String info = webBrowserInfo(request);
		dto.setDeviceInfor(info);

		BaseResponse<JSONObject> result = memberLoginServiceFeign.login(dto);
		if(!isSuccess(result)){
			setErrorMsg(model, result.getMsg());
			return MB_LOGIN_FTL;
		}
		// 3.登陆成功之后如何处理 保持会话信息 将token存入到cookie 里面 首页读取cookietoken 查询用户信息返回到页面展示
		JSONObject data = result.getData();
		String token = data.getString("token");
		CookieUtils.setCookie(request, response, WebConstants.LOGIN_TOKEN_COOKIENAME, token);
		return REDIRECT_INDEX;
	}

}
